//
//  Utils.m
//  Whatnet_iOS
//
//  Created by Bill on 2019/4/19.
//  Copyright © 2019 什么网络. All rights reserved.
//

#import "Utils.h"
#import <CommonCrypto/CommonCryptor.h>
static NSDictionary *consDict = nil;

@implementation Utils
/*字符串加密
 *参数
 *plainText : 加密明文
 *key        : 密钥 64位 为和后台约定的字段示例为xxxx
 */
+ (NSString *) encryptUseDES:(NSString *)plainText
{
    NSString *ciphertext = nil;
    const char *textBytes = [plainText UTF8String];
    NSUInteger dataLength = [plainText length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    Byte iv[] = { 1, 5, 3, 9, 4, 6, 2, 8 };
    //注:iv[] = { 0x12, 0x34, 0x56, 0x78,  0x90,  0xAB,  0xCD,  0xEF }为移动端和后台约定的字段
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [WNDESKey UTF8String], kCCKeySizeDES,
                                          iv,
                                          textBytes, dataLength,
                                          buffer, 1024,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        ciphertext = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    return ciphertext;
    
    
    
}
//解密
+ (NSString *) decryptUseDES:(NSString*)cipherText
{
    
    NSData* cipherData = [[NSData alloc] initWithBase64EncodedString:cipherText options:0];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    Byte iv[] = { 1, 5, 3, 9, 4, 6, 2, 8 };
    //注:iv[] = { 0x12, 0x34, 0x56, 0x78,  0x90,  0xAB,  0xCD,  0xEF }为移动端和后台约定的字段
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [WNDESKey UTF8String],
                                          kCCKeySizeDES,
                                          iv,
                                          [cipherData bytes],
                                          [cipherData length],
                                          buffer,
                                          1024,
                                          &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return plainText;
    
}

//dict的所有key的value值拼接字符串
+(NSString *) stringWithAllValue:(NSDictionary *)dict
{
    NSMutableString * getSignString = [NSMutableString string];
    NSArray * keyArr = [dict allKeys];
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    
    NSArray *newKeyArr = [keyArr sortedArrayUsingComparator:sort];
    for (NSString *key in newKeyArr) {
        NSString *value = [dict objectForKey:key];
        value = [NSString stringWithFormat:@"%@",value];
        [getSignString appendString:value];
    }
    return getSignString;
}

//sign校验
+(BOOL) stringWithData:(id)data message:(NSString*)msg sign:(NSString*)sign
{
    NSString * getSignString = [NSString string];
    if([data isKindOfClass:[NSDictionary class]]||[data isKindOfClass:[NSArray class]]){
        getSignString =[NSString stringWithFormat:@"code=0&data=%@&msg=%@",WNCLIENT_SALT,msg];
    }
    else if (!data){
        getSignString =[NSString stringWithFormat:@"code=0&data=&msg=%@",msg];
    }
    else{
        getSignString =[NSString stringWithFormat:@"code=0&data=%@&msg=%@",data,msg];
    }
    NSLog(@"%@",[getSignString MD5]);
    if ([sign isEqualToString:[getSignString MD5]]) {
        return YES;
    }else{
        return NO;
    }
}

//是否是有效手机号
+(BOOL)isValidTelePhone:(NSString*)text{
    NSString*str = @"^1[0-9][0-9]\\d{8}$";//支持1开头的手机号码
    return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str] evaluateWithObject:text];
}

//是否越狱
+ (BOOL)isJailBreak
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
        NSLog(@"The device is jail broken!");
        return YES;
    }
    NSLog(@"The device is NOT jail broken!");
    return NO;
}

+ (UIImage *)getFilterImage:(NSString *)imageName{
    NSString * path = [[NSBundle mainBundle] pathForResource:@"FilterResource" ofType:@"bundle"];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",imageName]];
    return [UIImage imageWithContentsOfFile:path];
}

/*
 m:月份
 d:日期
 */
//星座
+(NSString *)getAstroWithMonth:(int)m day:(int)d
{
    
    NSString *astroString = @"摩羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    if (m<1||m>12||d<1||d>31){
        
        return @"日期格式有误";
    }
    if(m==2 && d>29){
        return @"错误日期格式!!";
    }
    else if(m==4 || m==6 || m==9 || m==11) {
        
        if (d>30) {
            return @"错误日期格式!!!";
            
        }
        
    }
    
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];
    
    return result;
    
}


//根据星座获取时间段
+(NSString *)getDateWithConstellation:(NSString*)Constellation{
    if (!Constellation) {
        Constellation = @"";
    }
    if (!consDict) {
        consDict = @{@"白羊座":@"3月21日～4月19日",
                     @"金牛座":@"4月20日～5月20日",
                     @"双子座":@"5月21日～6月20日",
                     @"巨蟹座":@"6月21日～7月22日",
                     @"狮子座":@"7月23日～8月22日",
                     @"处女座":@"8月23日～9月22日",
                     @"天秤座":@"9月23日～10月22日",
                     @"天蝎座":@"10月23日～11月22日",
                     @"射手座":@"11月23日～12月21日",
                     @"摩羯座":@"12月22日～1月19日",
                     @"水瓶座":@"1月20日～2月18日",
                     @"双鱼座":@"2月20日～3月20日"};
    }
    NSString *string = consDict[Constellation];
    return string;
}

//将秒时间转为00:00
+ (NSString *)timeIntervalFormatToString:(NSTimeInterval)time {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //毫秒 SS
    [formatter setDateFormat:@"mm:ss"];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *startDate = [cal startOfDayForDate:[NSDate new]];
    NSDate *date = [startDate dateByAddingTimeInterval:time];
    return [formatter stringFromDate:date];
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)topViewController
{
    UIViewController *resultVC;
    resultVC = [Utils _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [Utils _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [Utils _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [Utils _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}
+ (CGSize)sizeWithFont:(UIFont *)font width:(CGFloat)width content:(NSString *)content
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    CGSize size = CGSizeMake(width,CGFLOAT_MAX);
    return [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

//当数据大于某个值时转换成带单位的
+ (NSString *)switchCount:(NSInteger)count{
    NSString *onlineCountStr;
    if (count < 0) {
        count = 0;
    }
    if(count > 10000 && count < 100000000){
        onlineCountStr = [self decimalwithFormat:@"0.0" floatV:(float)(count) * 0.0001];
        onlineCountStr = [NSString stringWithFormat:@"%@W",onlineCountStr];
    }else if (count <= 10000){
        onlineCountStr = [@(count) stringValue];
    }else{
        onlineCountStr = [self decimalwithFormat:@"0.0" floatV:(float)(count) * 0.00000001];
        onlineCountStr = [NSString stringWithFormat:@"%@亿",onlineCountStr];
    }
    return onlineCountStr;
}

+ (NSString *) decimalwithFormat:(NSString *)format  floatV:(float)floatV
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithFloat:floatV]];
}

@end
